package com.brayan.webapp.repository.usermgmt;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.apache.log4j.Logger;

import com.brayan.webapp.model.usermgmt.Role;
import com.brayan.webapp.model.usermgmt.Role_;

@Stateless
public class RoleRepository {
	@Inject
	private Logger LOGGER;

	@PersistenceContext
	private EntityManager em;
	
	public Role findById(Long id) {
		return em.find(Role.class, id);
	}
	
	public Role findRoleByName(String role){
		String roleUpperCased = role.toUpperCase();
		
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Role> criteria = cb.createQuery(Role.class);
		Root<Role> roleRoot = criteria.from(Role.class);
		// Swap criteria statements if you would like to try out type-safe
		// criteria queries, a new
		// feature in JPA 2.0
		// criteria.select(User).where(cb.equal(User.get(User_.name), email));
		criteria.select(roleRoot).where(cb.equal(roleRoot.get(Role_.role), roleUpperCased));
		return em.createQuery(criteria).getSingleResult();
	}
}
